package com.zz.inventory.service.impl;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.zz.inventory.domain.FranchiseBills;
import com.zz.inventory.domain.FranchisePackages;
import com.zz.inventory.feign.InventoryService;
import com.zz.inventory.service.IFranchiseBillsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.example.dto.SchoolPackageRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Log4j2
public class PackageService {
    @Autowired
    private IFranchiseBillsService iFranchiseBillsService;

    @Autowired
    private InventoryService inventoryService;

    @GlobalTransactional     // Seata全局事务注解：标记该方法为分布式事务入口
    public void createPackageAndSchoolRecord(FranchisePackages packageData, Long userId) {
        // 生成账单（保持原有逻辑不变）
        String billNo = "BILL" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
        FranchiseBills fr = new FranchiseBills();
        fr.setPackageId(packageData.getPackageId());
        fr.setServiceYears(packageData.getServiceYears());
        fr.setAmount(packageData.getFeeAmount());
        fr.setStatus("待支付");
        fr.setSchoolId(packageData.getSchool() != null ? packageData.getSchool().intValue() : null);
        fr.setBillNo(billNo);
        Date currentDate = new Date();
        // 24小时对应的毫秒数，1小时 = 3600000 毫秒，24小时 = 24 * 3600000 = 86400000 毫秒
        long twentyFourHoursLater = currentDate.getTime() + 24 * 3600000;
        Date dueDate = new Date(twentyFourHoursLater);
        fr.setDueDate(dueDate);
        int rows = iFranchiseBillsService.insertFranchiseBills(fr);
        if (rows <= 0) {
            throw new RuntimeException("账单创建失败"); // 直接抛异常触发回滚
        }


        // 构建DTO并调用学校服务
        SchoolPackageRecordDTO dto = SchoolPackageRecordDTO.builder()
                .userId(userId)
                .schoolId(packageData.getSchool().longValue())
                .packageId(packageData.getPackageId())
                .billId(fr.getBillId())
                .billNo(billNo)
                .serviceYears(packageData.getServiceYears())
                .build();
        // 调用远程服务（schoolmanage）的add方法，传入DTO，获取HTTP响应
        ResponseEntity<AjaxResult> response = inventoryService.add(dto);
        log.info("远程调用响应状态码: {}", response.getStatusCodeValue());// 输出远程调用的HTTP状态码（如200、500）
        log.info("远程调用业务状态码: {}", response.getBody().get("code")); // 输出远程服务返回的业务状态码（如200=成功）
        // 判断远程调用是否成功：HTTP状态码不是2xx（如400、500），或业务状态码不是"200"
        if (!response.getStatusCode().is2xxSuccessful()
                || !"200".equals(String.valueOf(response.getBody().get("code")))) {
            String errorMsg = String.valueOf(response.getBody().get("msg"));// 获取远程服务返回的错误信息
            throw new RuntimeException("远程调用失败: " + errorMsg);// 抛异常触发回滚
        }
    }
}
